import { useMessages } from "@renderer/queries/hooks/use-messages";
import { useLanguageSetting } from "@renderer/queries/hooks/use-settings";
import { useThread } from "@renderer/queries/hooks/use-threads";
import { EventNames, emitter } from "@renderer/services/event-service";
import logger from "@shared/logger/renderer-logger";
import type { Thread } from "@shared/triplit/types";
import { snapdom } from "@zumer/snapdom";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import {
  create302Watermark,
  createContentContainer,
  createScreenshotWrapper,
  generateScreenshotFilename,
  getScreenshotOptions,
  prepareMessageContent,
} from "./screenshot-helpers";
import { useActiveTab } from "./use-active-tab";
import { useActiveThread } from "./use-active-thread";
import { useMessageCopy } from "./use-message-copy";
import { usePrivacyMode } from "./use-privacy-mode";
import { useThreadMenu } from "./use-thread-menu";
import { useToolBar } from "./use-tool-bar";

interface HookParams {
  id: string;
  index: number;
  threadId: string;
}

const { tabService, threadService, shellService } = window.service;

export function useDragableTab({ id, threadId }: HookParams) {
  const { setActiveTabId, tabs } = useActiveTab();
  const { setActiveThreadId } = useActiveThread();
  const { confirmSwitchFromPrivate } = usePrivacyMode();
  const { selectedModelId } = useToolBar();
  const { privacyState } = usePrivacyMode();
  const { t } = useTranslation();
  const { data: lang } = useLanguageSetting();
  const [cleanModalOpen, setCleanModalOpen] = useState<"clean-messages" | null>(
    null,
  );

  // 获取当前tab对应的thread和messages
  const { data: thread } = useThread(threadId || "");
  const { data: messages } = useMessages({
    enabled: !!threadId,
    select: (data) =>
      data
        .filter((m) => m.threadId === threadId)
        .sort(
          (a, b) =>
            new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
        ),
  });

  const { handleCleanMessages: threadMenuHandleCleanMessages } = useThreadMenu(
    thread as Thread,
  );
  const { extractFullMessageContent, handleCopy } = useMessageCopy();

  const closeModal = useCallback(() => {
    setCleanModalOpen(null);
  }, []);

  const handleTabReload = useCallback(async () => {
    emitter.emit(EventNames.TAB_RELOAD, { tabId: id });
  }, [id]);

  const handleTabClose = useCallback(async () => {
    try {
      const canClose = await confirmSwitchFromPrivate("close this tab");
      if (!canClose) {
        return;
      }

      const nextActiveTabId = await tabService.deleteTab(id);
      emitter.emit(EventNames.TAB_CLOSE, { tabId: id, nextActiveTabId });
    } catch (error) {
      logger.error("Error closing tab", { error });
    }
  }, [id, confirmSwitchFromPrivate]);

  const handleTabCloseAll = useCallback(async () => {
    try {
      await tabService.deleteAllTabs();
      emitter.emit(EventNames.TAB_CLOSE_ALL, null);
    } catch (error) {
      logger.error("Error closing all tabs", { error });
    }
  }, []);

  const handleTabCloseOthers = useCallback(async () => {
    try {
      // await setActiveTabId(id);
      await tabService.deleteOtherTabs(id);
    } catch (error) {
      logger.error("Error closing other tabs", { error });
    }
  }, [id]);

  const handleTabCloseRight = useCallback(async () => {
    try {
      // await setActiveTabId(id);
      await tabService.deleteRightTabs(id);
    } catch (error) {
      logger.error("Error closing right tabs", { error });
    }
  }, [id]);

  const handleNewTab = useCallback(async () => {
    try {
      const newTab = await tabService.insertTab({
        title: t("thread.new-thread-title"),
        type: "thread",
        path: "/",
        isPrivate: false,
      });
      setActiveTabId(newTab.id);
      setActiveThreadId("");
    } catch (error) {
      logger.error("Error creating new tab", { error });
    }
  }, [setActiveTabId, setActiveThreadId, t]);

  const handleGenerateTitle = useCallback(async () => {
    try {
      // 找到当前标签页对应的线程
      const currentTab = tabs.find((tab) => tab.id === id);
      if (!currentTab?.threadId) {
        logger.warn("No thread associated with this tab");
        return;
      }
      const { isOk, errorMsg } = await threadService.summaryTitle(
        currentTab.threadId,
      );

      if (!isOk) {
        toast.error(t("thread-menu.actions.generate-title.error"));
        logger.error("ThreadMenu:handleGenerateTitle error", {
          errorMsg,
        });
      }
    } catch (error) {
      logger.error("Error generating title", { error });
    }
  }, [id, tabs, t]);

  const handleCleanMessages = useCallback(async () => {
    try {
      if (!threadId) {
        logger.warn("No thread associated with this tab");
        return;
      }

      await threadMenuHandleCleanMessages();
      closeModal();
    } catch (error) {
      logger.error("Error cleaning messages", { error });
    }
  }, [threadId, threadMenuHandleCleanMessages, closeModal]);

  const handleCreateBranch = useCallback(async () => {
    try {
      if (!threadId || !thread || !messages?.length) {
        logger.warn("No thread or messages available for branch creation");
        return;
      }
      // 获取最后一条消息作为分支起点
      const lastMessage = messages[messages.length - 1];
      if (!lastMessage) {
        logger.warn("No messages found to create branch from");
        return;
      }

      await threadService.createNewBranch(
        lastMessage,
        t("context-menu.new-thread-title", { keyPrefix: "message" }),
        selectedModelId,
        thread.providerId,
        privacyState?.isPrivate || false,
        "without-send-message",
      );
    } catch (error) {
      logger.error("Error creating new branch:", { error });
      toast.error(
        t("context-menu.create-new-branch-error", { keyPrefix: "message" }),
      );
    }
  }, [threadId, thread, messages, selectedModelId, privacyState, t]);

  const handleCopyAllMessages = useCallback(async () => {
    try {
      if (!messages?.length) {
        toast.error(t("message.copy-failed"));
        return;
      }

      // 拼接所有消息内容
      const allContent = messages
        .map((message) => extractFullMessageContent(message.content || ""))
        .join("\n\n");

      await handleCopy(allContent);
    } catch (error) {
      logger.error("Error copying all messages:", { error });
      toast.error(t("message.copy-failed"));
    }
  }, [messages, extractFullMessageContent, handleCopy, t]);

  const handleCopyLatestAIMessage = useCallback(async () => {
    try {
      if (!messages?.length) {
        toast.error(t("message.copy-failed"));
        return;
      }

      const latestAIMessage = messages
        .slice()
        .reverse()
        .find(
          (message) => message.role === "assistant" && message.content?.trim(),
        );

      if (!latestAIMessage) {
        toast.error(t("message.copy-failed"));
        return;
      }

      // 直接使用content字段，它已经包含了完整的内容
      const content = latestAIMessage.content || "";

      await handleCopy(content);
    } catch (error) {
      logger.error("Error copying latest AI message:", { error });
      toast.error(t("message.copy-failed"));
    }
  }, [messages, handleCopy, t]);

  const handleOpenInBrowser = useCallback(() => {
    const currentTab = tabs.find((tab) => tab.id === id);
    if (currentTab?.type === "302ai-tool" && currentTab.path) {
      const match = currentTab.path.match(/\/302ai-tool\/(.+)/);
      if (match) {
        const subdomain = match[1];
        const url = `https://${subdomain}.302.ai?lang=${lang}`;
        shellService.openExternal(url);
      }
    }
  }, [id, tabs, lang]);

  const handleScreenshotChat = useCallback(async () => {
    try {
      // 查找消息列表容器
      const messageListContainer = document.querySelector(
        '[data-screenshot-target="message-list"]',
      );

      if (!messageListContainer) {
        logger.warn("Message list container not found for screenshot");
        return;
      }

      const isDarkMode = document.documentElement.classList.contains("dark");

      // 使用辅助函数构建截图元素
      const wrapper = createScreenshotWrapper(isDarkMode);
      const contentContainer = createContentContainer();
      const messageContent = prepareMessageContent(messageListContainer);
      const watermark = create302Watermark(isDarkMode);

      // 组装 DOM
      contentContainer.appendChild(messageContent);
      wrapper.appendChild(contentContainer);
      wrapper.appendChild(watermark);
      document.body.appendChild(wrapper);

      // 获取截图配置
      const options = getScreenshotOptions(isDarkMode);

      // 生成截图并下载
      const result = await snapdom(wrapper, options);

      // 清理临时元素
      document.body.removeChild(wrapper);

      // 生成文件名
      const filename = generateScreenshotFilename(thread?.title);

      await result.download({
        format: "png",
        filename: filename,
      });
    } catch (error) {
      logger.error("Error taking screenshot:", { error });
    }
  }, [thread]);

  useEffect(() => {
    const handleThreadRename = async (event: {
      threadId: string;
      newTitle: string;
    }) => {
      const tabToUpdate = tabs.find((tab) => tab.threadId === event.threadId);
      if (tabToUpdate) {
        await tabService.updateTab(tabToUpdate.id, { title: event.newTitle });
      }
    };

    const handleThreadDelete = async (event: { threadId: string }) => {
      const tabToDelete = tabs.find((tab) => tab.threadId === event.threadId);
      if (tabToDelete) {
        await tabService.deleteTab(tabToDelete.id);
      }
    };

    const handleThreadDeleteAll = async (event: { threadIds: string[] }) => {
      const tabsToDelete = event.threadIds
        .map((threadId) => tabs.find((tab) => tab.threadId === threadId))
        .filter((tab) => tab !== undefined);

      if (tabsToDelete.length > 0) {
        try {
          await Promise.all(
            tabsToDelete.map((tab) => tabService.deleteTab(tab.id)),
          );
        } catch (error) {
          logger.error("Error deleting tabs", { error });
        }
      }
    };

    const unsubscribes = [
      emitter.on(EventNames.THREAD_RENAME, handleThreadRename),
      emitter.on(EventNames.THREAD_DELETE, handleThreadDelete),
      emitter.on(EventNames.THREAD_DELETE_ALL, handleThreadDeleteAll),
    ];

    return () =>
      unsubscribes.forEach((unsubscribe) => {
        unsubscribe();
      });
  }, [tabs]);

  return {
    handleTabClose,
    handleTabReload,
    onDragStart: () => {
      setActiveTabId(id);
    },
    handleTabCloseAll,
    handleTabCloseOthers,
    handleTabCloseRight,
    handleNewTab,
    handleGenerateTitle,
    handleCleanMessages,
    handleCreateBranch,
    handleCopyAllMessages,
    handleCopyLatestAIMessage,
    handleOpenInBrowser,
    handleScreenshotChat,
    cleanModalOpen,
    setCleanModalOpen,
    closeModal,
  };
}
